package pers.liu.yibandemo.service;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 生成和验证一次性令牌
 */
@Service
public class OneTimeTokenService {
    private final Map<String, TokenInfo> tokenStore = new ConcurrentHashMap<>();

    @Scheduled(cron = "0 0 0 * * ?") // 每天凌晨执行一次
    public void clearExpiredTokens() {
        // 遍历令牌存储，删除过期的令牌
        tokenStore.entrySet().removeIf(entry -> isTokenExpired(entry.getKey()));
    }

    public String generateToken(String userId) {
        // 检查是否已存在有效的令牌
        for (Map.Entry<String, TokenInfo> entry : tokenStore.entrySet()) {
            TokenInfo tokenInfo = entry.getValue();
            if (tokenInfo != null && tokenInfo.getUserId() != null && tokenInfo.getUserId().equals(userId) && !isTokenExpired(entry.getKey())) {
                return entry.getKey(); // 返回已存在的有效令牌
            }
        }
        // 如果没有有效令牌，生成新的令牌
        String token = UUID.randomUUID().toString();
        long currentTime = System.currentTimeMillis();
        TokenInfo tokenInfo = new TokenInfo(userId, currentTime);
        tokenStore.put(token, tokenInfo);
        return token;
    }

    private boolean isTokenExpired(String token) {
        TokenInfo tokenInfo = tokenStore.get(token);
        if (tokenInfo == null) {
            return true; // 令牌不存在，视为过期
        }

        long currentTime = System.currentTimeMillis();
        long tokenCreationTime = tokenInfo.getCreationTime();
        // 假设令牌的有效期是一天（86400000 毫秒）
        return (currentTime - tokenCreationTime) > 86400000;
    }

    public boolean verifyToken(String token, String userId) {
        try {
            String storedUserId = tokenStore.get(token).getUserId();
            if (storedUserId != null && storedUserId.equals(userId)) {
                return true;
            }
        } catch (Exception e) {
            return false;
        }
        return false;
    }

    private static class TokenInfo {
        private final String userId;
        private final long creationTime;

        public TokenInfo(String userId, long creationTime) {
            this.userId = userId;
            this.creationTime = creationTime;
        }

        public String getUserId() {
            return userId;
        }

        public long getCreationTime() {
            return creationTime;
        }
    }
}
